package de.zainodis.kitchengnome.ui;

import static junit.framework.Assert.assertNotNull;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.SeekBar;
import android.widget.TextView;
import de.zainodis.kitchengnome.R;
import de.zainodis.kitchengnome.domainmodel.ListItem;

/**
 * Editor for editing {@link ListItem}.
 * 
 * @author fzarrai
 * 
 */
public class FoodItemEditor extends BaseActivity {

	private static final String TAG = "FoodItemEditor";

	private ListItem target;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setTitle(R.string.edit);
		setContentView(R.layout.layout_edit_item);

		Intent parent = getIntent();
		target = parent.getParcelableExtra(ListItem.TYPE_NAME);
		assertNotNull(TAG + "Requires a valid FoodItem.", target);

		getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);

		// Pre-Fill all known details from the selected entry
		SeekBar amountBar = (SeekBar) findViewById(R.id.layout_edit_item_amount);
		amountBar.setProgress(target.getAmount());

		TextView nameField = (TextView) findViewById(R.id.layout_edit_item_name);
		nameField.setText(target.getName());

		TextView notesField = (TextView) findViewById(R.id.layout_edit_item_notes);
		notesField.setText(target.getNotes());
	}

	public void onSave(View cause) {
		// Load edited details
		target.setAmount(((SeekBar) FoodItemEditor.this.findViewById(R.id.layout_edit_item_amount)).getProgress());
		target.setName(((TextView) FoodItemEditor.this.findViewById(R.id.layout_edit_item_name)).getText().toString());
		target.setNotes(((TextView) FoodItemEditor.this.findViewById(R.id.layout_edit_item_notes)).getText().toString());
		// Persist changes
		getListEntryDao().saveItem((ListItem) target);

		Intent intent = getIntent();
		setResult(RESULT_OK, intent);
		finish();

	}

	public void onCancel(View cause) {
		Intent intent = getIntent();
		setResult(RESULT_CANCELED, intent);
		finish();
	}
}
